package com.jlh.netty.client;

import com.jlh.netty.Command;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/**
 * com.jlh.netty.client
 * Created by ASUS on 2017/4/11.
 * 19:19
 */
public class HelloClient {
    public static String host = "127.0.0.1";
    public static int port = 7878;
    public static void main(String[] args) throws IOException, InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ObjectClientInitializer());

            // 连接服务端
            Channel ch = b.connect(host, port).sync().channel();

            // 控制台输入
            Scanner in = new Scanner((System.in));
            for (; ; ) {
                String code = in.nextLine();
                String value = in.nextLine();
                Command c = new Command();
                c.setCode(code);
                c.setValue(value);
                /*
                 * 向服务端发送在控制台输入的文本 并用"\r\n"结尾
                 * 之所以用\r\n结尾 是因为我们在handler中添加了 DelimiterBasedFrameDecoder 帧解码。
                 * 这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识别和解码
                 * */
                ch.writeAndFlush(c);
            }
        }
        finally{
            group.shutdownGracefully();
        }
    }

}

